package com.ls.rabbitmqService.base;

import com.ls.rabbitmqService.utils.ConnectionFactoryUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Recv {
    private final static String QUEUE_NAME="test";
    public static void main(String[] args){
        Connection connection =null;
        Channel channel=null;
        try {
            connection = ConnectionFactoryUtil.getRabbitConnection();
            channel = connection.createChannel();

            //queue的持久化设置需要与这个队列本省设置的一致否则报错
            channel.queueDeclare(QUEUE_NAME,true,false,false,null);
            System.out.println("[*] waiting for message To exit press ");
            final Channel copyChannel=channel;
            Consumer consumer=new DefaultConsumer(copyChannel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    copyChannel.basicAck(envelope.getDeliveryTag(),false);
                    String message=new String(body,"utf-8");
                    System.out.println(String.format("[X] received %s",message));
                }
            };
            /**
             * 消息确认机制改为手动确认  copyChannel.basicAck(envelope.getDeliveryTag(),false);
             */
            channel.basicConsume(QUEUE_NAME,false,consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            /*if(channel!=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
        }
    }
}
